#!/usr/bin/env bash
chmod 777 /root/wordpress/my-wordpress-wpcli.tar
set -euo pipefail

# 检查是否已安装 Docker
check_docker_version() {
    REQUIRED_VERSION="20.10.0"

    # 检查 Docker 是否安装
    if ! command -v docker &> /dev/null; then
        echo "Docker 未安装，正在安装..."
        install_docker
    else
        INSTALLED_VERSION=$(docker --version 2>/dev/null | awk '{print $3}' | sed 's/,//')
        echo "Docker 已安装，版本: $INSTALLED_VERSION"
        
        if [[ -z "$INSTALLED_VERSION" || "$INSTALLED_VERSION" == "unknown" ]]; then
            echo "Docker 版本信息不可用，正在重新安装..."
            install_docker
        else
            if [[ "$(printf '%s\n' "$REQUIRED_VERSION" "$INSTALLED_VERSION" | sort -V | head -n1)" != "$REQUIRED_VERSION" ]]; then
                echo "当前 Docker 版本低于要求的版本 $REQUIRED_VERSION，建议更新。"
            else
                echo "Docker 版本符合要求，无需更新。"
            fi
        fi
    fi
}

# 检查 Docker Compose 版本是否符合要求（大于等于2版本）
check_docker_compose_version() {
    if docker-compose --version 2>/dev/null | grep -q "v2"; then
        echo "Docker Compose 已安装，版本符合要求，跳过安装。"
    else
        echo "Docker Compose 未安装或版本低于要求，正在安装..."
        install_docker_compose
    fi
}

# 安装 Docker
install_docker() {
    echo "=== 安装 Docker ==="
    apt update -y
    apt install -y docker.io
    systemctl enable docker
    systemctl start docker
    echo "Docker 安装完成"
}

# 安装 Docker Compose
install_docker_compose() {
    echo "=== 安装 Docker Compose ==="
    curl -L "https://github.com/docker/compose/releases/download/v2.37.3/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
    chmod +x /usr/local/bin/docker-compose
    echo "Docker Compose 安装完成"
}

# 检查并安装/更新 Docker 和 Docker Compose
check_docker_version
check_docker_compose_version

# 配置 Docker
echo "=== 配置 Docker ==="
cat > /etc/docker/daemon.json << EOF
{
    "insecure-registries": ["172.21.100.16:9998"],
    "data-root": "/data/docker",
    "log-opts": {"max-size": "10m", "max-file": "1"},
    "exec-opts": ["native.cgroupdriver=systemd"],
    "live-restore": true
}
EOF
systemctl restart docker

# 创建工作目录
mkdir -p /data/wp/config /data/wp/data
cd /data/wp
rm -f ~/.wpinstall_config

WP_PORT=8888
echo "wp_port:$WP_PORT" >> ~/.wpinstall_config

SERVER_IP="$(curl -s ifconfig.me)"
WP_URL="http://${SERVER_IP}:${WP_PORT}"

# 生成随机密码
generate_password() {
    openssl rand -base64 12 | tr -d '+/=' | cut -c1-16
}

MYSQL_ROOT_PASSWORD=$(generate_password)
MYSQL_DATABASE=wordpress
MYSQL_USER=wpuser
MYSQL_PASSWORD=$(generate_password)
ADMIN_USER="aNtvbM8gXURLpPAW"
ADMIN_PASSWORD="LsBmuqFh6MC2pMyMmKbY"
ADMIN_EMAIL="office@gmail.com"

# 生成安全密钥
generate_secure_keys() {
    SECURE_KEY_1=$(openssl rand -base64 32)
    SECURE_KEY_2=$(openssl rand -base64 32)
    SECURE_KEY_3=$(openssl rand -base64 32)
    SECURE_KEY_4=$(openssl rand -base64 32)
    SECURE_KEY_5=$(openssl rand -base64 32)
    SECURE_KEY_6=$(openssl rand -base64 32)
    SECURE_KEY_7=$(openssl rand -base64 32)
    SECURE_KEY_8=$(openssl rand -base64 32)
}

# 生成配置文件
generate_wp_config() {
    CONFIG_DIR="/data/wp/config"
    mkdir -p "$CONFIG_DIR"
    
    cat > "$CONFIG_DIR/wp-config.php" << _EOF_
<?php
define( 'DB_NAME', '${MYSQL_DATABASE}' );
define( 'DB_USER', '${MYSQL_USER}' );
define( 'DB_PASSWORD', '${MYSQL_PASSWORD}' );
define( 'DB_HOST', 'db:3306' );
define( 'DB_CHARSET', 'utf8' );
define( 'WP_ADMIN_USER', '${ADMIN_USER}' );
define( 'WP_ADMIN_PASSWORD', '${ADMIN_PASSWORD}' );
define( 'WP_ADMIN_EMAIL', '${ADMIN_EMAIL}' );
define( 'WP_HOME', '${WP_URL}' );
define( 'WP_SITEURL', '${WP_URL}' );
define( 'WPLANG', 'zh_CN' );
define( 'AUTH_KEY', '${SECURE_KEY_1}' );
define( 'SECURE_AUTH_KEY', '${SECURE_KEY_2}' );
define( 'LOGGED_IN_KEY', '${SECURE_KEY_3}' );
define( 'NONCE_KEY', '${SECURE_KEY_4}' );
define( 'AUTH_SALT', '${SECURE_KEY_5}' );
define( 'SECURE_AUTH_SALT', '${SECURE_KEY_6}' );
define( 'LOGGED_IN_SALT', '${SECURE_KEY_7}' );
define( 'NONCE_SALT', '${SECURE_KEY_8}' );
\$table_prefix = 'wp_';
define( 'WP_DEBUG', false );
define( 'ABSPATH', __DIR__ . '/' );
require_once ABSPATH . 'wp-settings.php';
_EOF_

    echo "配置文件已生成: $CONFIG_DIR/wp-config.php"
}

# 保存配置
echo "MYSQL_ROOT_PASSWORD:${MYSQL_ROOT_PASSWORD}" >> ~/.wpinstall_config
echo "MYSQL_DATABASE:wordpress" >> ~/.wpinstall_config
echo "MYSQL_USER:wpuser" >> ~/.wpinstall_config
echo "MYSQL_PASSWORD:${MYSQL_PASSWORD}" >> ~/.wpinstall_config
echo "admin_user:${ADMIN_USER}" >> ~/.wpinstall_config
echo "admin_password:${ADMIN_PASSWORD}" >> ~/.wpinstall_config
echo "admin_email:${ADMIN_EMAIL}" >> ~/.wpinstall_config
echo "wp_url:${WP_URL}" >> ~/.wpinstall_config

echo "=== 配置信息 ==="
echo "MySQL Root 密码: ${MYSQL_ROOT_PASSWORD}"
echo "WordPress 数据库: wordpress"
echo "数据库用户: wpuser"
echo "数据库密码: ${MYSQL_PASSWORD}"
echo "管理员用户: ${ADMIN_USER}"
echo "管理员密码: ${ADMIN_PASSWORD}"
echo "访问地址: ${WP_URL}"
echo "================="

# 生成密钥和配置
generate_secure_keys
generate_wp_config

# 创建Docker Compose文件（兼容v2格式）
cat > docker-compose.yaml << _EOF_
version: '3.8'

services:
  db:
    image: mysql:8.0
    environment:
      MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
      MYSQL_DATABASE: wordpress
      MYSQL_USER: wpuser
      MYSQL_PASSWORD: ${MYSQL_PASSWORD}
      TZ: Asia/Shanghai
    volumes:
      - ./data/db:/var/lib/mysql
    ports:
      - "3306:3306"
    healthcheck:
      test: ["CMD", "mysqladmin", "ping", "-h", "localhost"]
      interval: 5s
      retries: 10

  wordpress:
    image: my-wordpress-wpcli:latest
    depends_on:
      - db
    environment:
      WORDPRESS_DB_HOST: db:3306
      WORDPRESS_TABLE_PREFIX: wp_
      TZ: Asia/Shanghai
    volumes:
      - ./data/html:/var/www/html
      - ./config/wp-config.php:/var/www/html/wp-config.php:ro
    ports:
      - "${WP_PORT}:80"
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:80"]
      interval: 10s
      timeout: 5s
      retries: 5
_EOF_

# 解压并加载 Docker 镜像

TAR_FILE="/root/wordpress/my-wordpress-wpcli.tar"
echo "正在加载 Docker 镜像文件: $TAR_FILE"
if [ -f "$TAR_FILE" ]; then
    echo "解压并加载 Docker 镜像: $TAR_FILE"
    docker load -i "$TAR_FILE"
else
    echo "未找到 Docker 镜像文件: $TAR_FILE"
fi

# 启动服务
echo "=== 启动 WordPress 服务 ==="
docker-compose up -d

# 等待数据库服务健康启动
echo "=== 等待数据库服务启动 ==="
until docker exec wp-db-1 mysql -u root -p"${MYSQL_ROOT_PASSWORD}" -e "SHOW DATABASES;" | grep -q "${MYSQL_DATABASE}"; do
  echo "等待数据库启动..."
  sleep 5
done

# 初始化 WordPress
docker exec -i wp-wordpress-1 wp core install \
    --url="${WP_URL}" \
    --title="user" \
    --admin_user="${ADMIN_USER}" \
    --admin_password="${ADMIN_PASSWORD}" \
    --admin_email="${ADMIN_EMAIL}" \
    --allow-root

echo "=== 安装完成 ==="
echo "访问地址: ${WP_URL}"
echo "管理员账号: ${ADMIN_USER}"
echo "管理员密码: ${ADMIN_PASSWORD}"

echo "=== 安装nginx ==="
apt install -y nginx jq unzip
sed -i '/^[[:space:]]*http[[:space:]]*{/a\        client_max_body_size 500m;' /etc/nginx/nginx.conf
systemctl restart nginx

echo "=== 安装acme.sh ==="
cd ~
git clone --depth=1 https://github.com/acmesh-official/acme.sh.git
cd acme.sh

# 安装并配置 acme.sh
./acme.sh --install -m "my@example.com"
ln -sf ~/.acme.sh/acme.sh /usr/local/bin/acme.sh

